package com.oscar.springaidemo.web.controller;


import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.awt.*;
import java.util.Arrays;
import java.util.Date;

@RestController
@RequestMapping("/spring-ai")
public class OpenAiController {

    @Resource
    private ChatClient dashScopeChatClient;

    @Resource
    private ChatClient chatClient;


    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？")String query) {

        return dashScopeChatClient.prompt(query).call().content();
    }


    @GetMapping(value = "/stream/chat",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？")String query, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        Flux<String> flux = chatClient
                .prompt(query)
                .system(i->{
                    i.param("current_date",new Date());
                })
                .toolCallbacks(
                        Arrays.asList(

                        )
                )
//                .advisors(i->i.param())
                .stream()
                .content();

        flux.concatWith(Flux.just("[DONE]"));//返回相应表示，关闭SSE长连接

        return flux;

    }

}
